package com.up.vms.interfaces.rest.controller;

import com.alibaba.fastjson.JSON;
import com.up.vms.application.service.ActivityApplicationService;
import com.up.vms.domain.module.ActivityAdditionalInfoVO;
import com.up.vms.domain.module.ActivityDTO;
import com.up.vms.domain.module.ActivityDetailDTO;
import com.up.vms.domain.module.ActivityUploadAdditionalInfoVO;
import com.up.vms.domain.vm.entity.Activity;
import com.up.vms.infrastructure.constants.EmpAPIConstants;
import com.up.vms.infrastructure.mvc.BaseResponse;
import com.up.vms.infrastructure.mvc.GeneRespDTO;
import com.up.vms.infrastructure.mvc.RespCode;
import com.up.vms.infrastructure.mvc.ReturnCode;
import com.up.vms.infrastructure.util.CommonUtils;
import com.up.vms.infrastructure.util.DateUtil;
import com.up.vms.interfaces.rest.request.ActivityDetailRequest;
import com.up.vms.interfaces.rest.request.ActivityIdRequest;
import com.up.vms.interfaces.rest.request.ActivityRequest;
import com.up.vms.interfaces.rest.response.CommonResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Api(value = "活动管理", produces = "application/json")
@RequestMapping(EmpAPIConstants.API_ROOT)
@Slf4j
public class ActivityController {

    @Autowired
    private ActivityApplicationService activityApplicationService;

    // 列表查询
    @RequestMapping(value = "/activity/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取当前类型下的活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index", value = "页码", dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "每页记录数", dataType = "Integer")
    })
    @ResponseBody
    public BaseResponse activityList(
            @RequestParam(value = "activityName", required = false) String activityName,
            @RequestParam(value = "start", required = false) String startTime,
            @RequestParam(value = "end", required = false) String endTime,
            @RequestParam(value = "index") Integer index,
            @RequestParam(value = "size") Integer size) {

        GeneRespDTO geneRespDTO = null;
        CommonResponse commonResponse = new CommonResponse();
        ActivityDTO activityDTO = new ActivityDTO();

        try {
            if (CommonUtils.isNotNull(index)) {
                activityDTO.setPage(index);
            }
            if (CommonUtils.isNotNull(size)) {
                activityDTO.setSize(size);
            }
            if (CommonUtils.isNotNull(activityName)) {
                activityDTO.setActivityName(activityName);
            }
            if (CommonUtils.isNotNull(startTime)) {
                activityDTO.setStartTime(DateUtil.format(startTime, DateUtil.FORMAT_YMD));
            }
            if (CommonUtils.isNotNull(endTime)) {
                Date endDay = DateUtil.format(endTime, DateUtil.FORMAT_YMD);
//                Calendar calendar = new GregorianCalendar();
//                calendar.setTime(endDay);
//                calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
//                endDay = calendar.getTime();
                activityDTO.setEndTime(endDay);
            }

            geneRespDTO = activityApplicationService.getActivityList(activityDTO);

            commonResponse.setData(geneRespDTO.getData());
            commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));

        } catch (Exception e) {
            log.error("获取活动列表失败：{}", e.getMessage(), e.getCause());
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return commonResponse;
    }

    // 新增
    @RequestMapping(value = "/activity/save", method = RequestMethod.POST)
    public BaseResponse saveBanner(@RequestBody ActivityRequest request) {
        CommonResponse response = new CommonResponse();
        try {
            Activity activity = convertFromRequest(request);

            GeneRespDTO geneRespDTO = activityApplicationService.saveActivity(activity);

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }

    private Activity convertFromRequest(ActivityRequest request) throws Exception {
        Activity activity = new Activity();

        if (CommonUtils.isNotNull(request.getId())) {
            activity.setId(request.getId());
        }

        if (CommonUtils.isNotNull(request.getActivityName())) {
            activity.setActivityName(request.getActivityName());
        }

        activity.setActivityImage(request.getActivityImage());

        activity.setActivityDesc(request.getActivityDesc());

        if (CommonUtils.isNotNull(request.getAdditionalInfo())) {
            List<ActivityAdditionalInfoVO> list = request.getAdditionalInfo();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    ActivityAdditionalInfoVO vo = list.get(i);
                    vo.setSortNo(i);
                }
            }
//            Collections.sort(list, Comparator.comparing(ActivityAdditionalInfoVO::getSortNo));
            activity.setAdditionalInfo(JSON.toJSONString(list));
        }

        if (CommonUtils.isNotNull(request.getStartDate())) {
            activity.setStartDate(request.getStartDate());
        } else {
            throw new Exception("开始时间 startDate 不能为空");
        }

        if (CommonUtils.isNotNull(request.getEndDate())) {
            activity.setEndDate(request.getEndDate());
        } else {
            throw new Exception("结束时间 endDate 不能为空");
        }

        return activity;
    }

    // 删除
    @RequestMapping(value = "/activity/delete", method = RequestMethod.POST)
    public BaseResponse delete(@RequestBody ActivityIdRequest request) throws Exception {

        List<Long> idList = new ArrayList<>();

        if (CommonUtils.isNull(request.getIds())) {
            throw new Exception("shortId is null");
        }

        String activityId = request.getIds();
        if (activityId.contains(",")) {
            String[] cs = activityId.split(",");
            for (String s : cs) {
                idList.add(Long.valueOf(s));
            }
        } else{
            idList.add(Long.valueOf(activityId));
        }

        CommonResponse response = new CommonResponse();
        try {

            GeneRespDTO geneRespDTO = activityApplicationService.deleteActivity(idList);

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR.getCode(), ex.getMessage()));
        }

        return response;

    }

    // 上传用户列表
    @RequestMapping(value = "/activity/detail/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取当前类型下的活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "index", value = "页码", dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "每页记录数", dataType = "Integer")
    })
    @ResponseBody
    public BaseResponse activityDetailList(
            @RequestParam(value = "activityId", required = false) Long activityId,
            @RequestParam(value = "userName", required = false) String userName,
            @RequestParam(value = "start", required = false) String startTime,
            @RequestParam(value = "end", required = false) String endTime,
            @RequestParam(value = "index") Integer index,
            @RequestParam(value = "size") Integer size) {

        GeneRespDTO geneRespDTO = null;
        CommonResponse commonResponse = new CommonResponse();
        ActivityDetailDTO detailDTO = new ActivityDetailDTO();

        try {
            if (CommonUtils.isNotNull(index)) {
                detailDTO.setPage(index);
            }
            if (CommonUtils.isNotNull(size)) {
                detailDTO.setSize(size);
            }
            if (CommonUtils.isNotNull(activityId)) {
                detailDTO.setActivityId(activityId);
            } else {
                throw new Exception("activityId 不能为空");
            }
            if (CommonUtils.isNotNull(userName)) {
                detailDTO.setUserName(userName);
            }
            if (CommonUtils.isNotNull(startTime)) {
                detailDTO.setStartTime(DateUtil.format(startTime, DateUtil.FORMAT_YMD));
            }
            Date endDay = null;
            if (CommonUtils.isNotNull(endTime)) {
                endDay = DateUtil.format(endTime, DateUtil.FORMAT_YMD);
            } else if (CommonUtils.isNotNull(startTime)) {
                endDay = DateUtil.format(startTime, DateUtil.FORMAT_YMD);
            }

            if (endDay != null) {
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(endDay);
                calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
                endDay = calendar.getTime();
                detailDTO.setEndTime(endDay);
            }

            geneRespDTO = activityApplicationService.getActivityDetailList(detailDTO);

            commonResponse.setData(geneRespDTO.getData());
            commonResponse.setRespCode(new RespCode(ReturnCode.SUCCESS));

        } catch (Exception e) {
            log.error("获取用户列表失败：{}", e.getMessage(), e.getCause());
            commonResponse.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return commonResponse;
    }

    // 活动详情
    @RequestMapping(value = "/activity/{id}", method = RequestMethod.GET)
    public BaseResponse getById(@PathVariable(value = "id") Long id) {

        CommonResponse response = new CommonResponse();

        try {
            GeneRespDTO geneRespDTO = activityApplicationService.queryActivityById(id);

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }

    // 上传用户详情
    @RequestMapping(value = "/activity/detail/{id}", method = RequestMethod.GET)
    public BaseResponse getDetailById(@PathVariable(value = "id") Long id) {

        CommonResponse response = new CommonResponse();

        try {
            GeneRespDTO geneRespDTO = activityApplicationService.queryActivityDetailById(id);

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }

    // 上传用户详情
    @RequestMapping(value = "/activity/detail/user/delete", method = RequestMethod.POST)
    public BaseResponse deleteDetailById(@RequestBody ActivityDetailRequest request) {

        CommonResponse response = new CommonResponse();

        try {
            GeneRespDTO geneRespDTO = activityApplicationService.deleteActivityUser(request.getIds());

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }
}
